package service

import (
    "authserver/constants"
    "authserver/global"
    "authserver/model"
    "authserver/utils"
    "encoding/json"
    "errors"
    "fmt"
    "github.com/tidwall/gjson"
    "net/http"
    "net/url"
    "strings"
    "time"
)

var DID = ""
func KsUrlParse(shortUrl string,username string ) (err error,respVideo model.VideoResp) {

    // 先查下解析记录

    var logInfo model.ParseLog

    global.GVA_DB.Table(logInfo.TableName()).Where("short_url=?",shortUrl).Find(&logInfo)
    if logInfo.Id!=0{

        // 超时时间
        logTime,_:=time.ParseInLocation(constants.DayTime,logInfo.ParseTime,time.Local)

        if time.Now().Sub(logTime).Minutes()<30{
            respVideo=model.VideoResp{
                Id:logInfo.Id,
                Title: logInfo.Title,
                Image: logInfo.ImageUrl,
                Video: logInfo.VideoUrl,
            }
            return
        }
    }


    header := map[string]string{
        "User-Agent":                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
        "Connection":                "Keep-Alive",
        "Sec-Ch-Ua":                 `"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"`,
        "Sec-Ch-Ua-Mobile":          "?1",
        "Sec-Ch-Ua-Platform":        `"Windows"`,
        "Upgrade-Insecure-Requests": "1",
        "Accept":                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Sec-Fetch-Site":            "none",
        "Sec-Fetch-Mode":            "navigate",
        "Sec-Fetch-User":            "?1",
        "Sec-Fetch-Dest":            "document",
        "Accept-Language": "zh-CN,zh;q=0.9",

    }
    if DID!=""{
        cookieInfo:="kpf=PC_WEB; clientid=3; did="+DID+"; kpn=KUAISHOU_VISION"
        header["Cookie"]=cookieInfo
    }

    err, _, headerh := utils.Get(shortUrl, nil, header,nil)
    if err != nil {
        fmt.Println(err.Error())
        return err, respVideo
    }

    videoKey:=""

    nextUrl := headerh["Location"]
    nextUrl = strings.Replace(nextUrl, "&amp;", "&", -1)

    did:=headerh["did"]
    if did!=""{
        //cookieInfo:="kpf=PC_WEB; clientid=3; did="+did+"; kpn=KUAISHOU_VISION"
        //header["Cookie"]=cookieInfo
    }

    u,_:=url.Parse(nextUrl)
    if did==""{
        did=u.Query().Get("ztDid")
        if did!=""{
            cookieInfo:="kpf=PC_WEB; clientid=3; did="+did+"; kpn=KUAISHOU_VISION"
            header["Cookie"]=cookieInfo
        }
    }
    ss := strings.Split(u.Path, "/")
    videoKey=ss[len(ss)-1]

    // 第二步请求
    err, realVideoUrl, header2 := utils.Get(nextUrl, nil, header,nil)
    if err != nil {
        fmt.Println(err.Error())
        return err, respVideo
    }

    step3Url := header2["Location"]


    // 如果还是 有跳转地址，那就在继续跳转访问
    if step3Url!=""{
        step3Url = strings.Replace(step3Url, "&amp;", "&", -1)

        err, realVideoUrl, header2 = utils.Get(step3Url, nil, header,nil)
        if err != nil {
            fmt.Println(err.Error())
            return err, respVideo
        }

        step4Url := header2["Location"]
        step4Url = strings.Replace(step4Url, "&amp;", "&", -1)

        reqCookies:=make([]*http.Cookie,0)
        reqCookies = append(reqCookies, &http.Cookie{
            Name: "kpf",
            Value: "PC_WEB",
        })
        reqCookies = append(reqCookies, &http.Cookie{
            Name: "clientid",
            Value: "3",
        })
        reqCookies = append(reqCookies, &http.Cookie{
            Name: "did",
            Value: did,
        })
        reqCookies = append(reqCookies, &http.Cookie{
            Name: "kpn",
            Value: "KUAISHOU_VISION",
        })

        err, realVideoUrl, _ = utils.Get(step4Url, nil, header,reqCookies)
        if err != nil {
            fmt.Println(err.Error())
            return err, respVideo
        }
    }

    fmt.Println(realVideoUrl)
    if strings.Index(realVideoUrl,"{\"status\":2}")==0{
        // did 过期了，重新找一个
        DID = did
    }
    // 截取数据
    startIndex:=strings.Index(realVideoUrl,"window.__APOLLO_STATE")
    if startIndex==-1{
        global.GVA_LOG.Error("ks start index err")
        return errors.New("解析失败"), respVideo
    }

    realVideoUrl = realVideoUrl[startIndex+24:]

    endIndex:=strings.Index(realVideoUrl,"};")

    if endIndex==-1{
        global.GVA_LOG.Error("ks end index err")
        return errors.New("解析失败"), respVideo
    }

    realVideoUrl = realVideoUrl[:endIndex+1]

    //fmt.Println("222",realVideoUrl)
    //fmt.Println("222",videoKey)

    var ksVideo model.KsVideoInfo

    // 取地址
    videoDetail:=gjson.Get(realVideoUrl,"defaultClient.VisionVideoDetailPhoto:"+videoKey).String()

    err=json.Unmarshal([]byte(videoDetail),&ksVideo)
    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        DID=did
        return errors.New("解析失败"), respVideo
    }

    respVideo.Video=ksVideo.PhotoUrl
    respVideo.Title =ksVideo.Caption
    respVideo.Image = ksVideo.CoverUrl


    hostAddr:=""
    u,err=url.Parse(respVideo.Video)
    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return
    }
    hostAddr = u.Host

    parseLog:=model.ParseLog{
        ShortUrl:  shortUrl,
        VideoUrl:  respVideo.Video,
        ImageUrl:  respVideo.Image,
        Title:     respVideo.Title,
        Username:  username,
        HostAddr: hostAddr,
        ParseTime: time.Now().Format(constants.DayTime),
    }

    global.GVA_DB.Create(&parseLog)
    respVideo.Id = parseLog.Id
    return nil, respVideo

}
